"ui";
activity.window.addFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.window.setStatusBarColor(android.graphics.Color.TRANSPARENT);
activity.window.getDecorView().setSystemUiVisibility(android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE | android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
var random_up, auto_up_down ;

ui.layout(
    <vertical>
        <linear id="appbar" orientation="vertical" h="75">
            <View h="25" w="*"/>
            <frame h="50">
                <img id="back" src="@drawable/ic_arrow_back_black_48dp" padding="12" tint="#ffffff" w="50" h="50" foreground="?selectableItemBackground"/>
                <text id="app_name" textSize="18sp" textStyle="bold" textColor="#ffffff" w="*" text="选择视频" h="50" gravity="center"/>
            </frame>
        </linear>
        <frame h="*">
            <vertical>
                <vertical h="110">
                    <horizontal margin="15 5 15 5">
                        <text textSize="16" h="24" textColor="black" textStyle="bold" text="配置启动参数" w="0" layout_weight="1" gravity="center_vertical"/>
                        <card w="60" h="24" cardCornerRadius="5dp" cardElevation="0dp" gravity="center" layout_gravity="center">
                            <View w="*" h="*" bg="#FF0081FF"/>
                            <text id="app_start_setting" text="去设置" color="#FFFFFF"  gravity="center" size="14" bg="?attr/selectableItemBackground" clickable="true"/>
                        </card>
                    </horizontal>
                    <text id="app_params_desc" text="" color="black"  gravity="center_vertical" size="14" margin="15 5 15 5"/>
                </vertical>
                <View w="*" h="1" bg="#E0E0E0"/>
                <list id="video_list" layout_weight="1">
                <vertical h="109" w="*" foreground="?selectableItemBackground">
                    
                    <linear orientation="horizontal" margin="10 10 10 0" >
                        <linear orientation="vertical" h="*" w="40">
                            {/* <img src="{{app_icon}}" w="30" h="30" padding="3dp" foreground="?selectableItemBackground" /> */}
                            <checkbox id="app_check" h="*" w="*" checked="{{app_check}}" enabled="false" disabled="true"/>
                        </linear>

                        <linear orientation="vertical" layout_weight="1">
                            <linear orientation="horizontal" w="*" h="30">
                                {/* <img src="{{app_icon}}" w="30" h="30" padding="3dp" foreground="?selectableItemBackground" /> */}
                                <text id="app_name" textSize="16sp" textStyle="bold" textColor="black" text="{{app_name}}" h="30" gravity="center_vertical"/>
                            </linear>
                            <linear orientation="horizontal" w="*" h="24" marginTop="5">
                                <horizontal w="0" layout_weight="2" >
                                    <text text="邀请码：" textColor="#616161" textSize="15" w="*"/>
                                </horizontal>
                                <horizontal w="0" h="*" layout_weight="3" >
                                    <text id="app_yqm" text="{{app_yqm}}" textColor="#616161" textSize="15" w="*"/>
                                </horizontal>
                                <horizontal w="0" layout_weight="2" >
                                    <card w="*" h="*" cardCornerRadius="5dp" cardElevation="0dp" gravity="center" layout_gravity="center">
                                        <View w="*" h="*" bg="#F57C00"/>
                                        <text id="copy" text="复制" color="#FFFFFF"  gravity="center" size="14" bg="?attr/selectableItemBackground" clickable="true"/>
                                    </card>
                                </horizontal>
                            </linear>
                            {/* <linear orientation="horizontal" w="*" h="24">
                                <horizontal w="0" h="*" layout_weight="2" >
                                    <text text="收益比例：" textColor="black" textSize="15" w="*"/>
                                </horizontal>
                                <horizontal w="0" h="*" layout_weight="5" >
                                    <text id="app_syb" text="{{app_syb}}" textColor="black" textSize="15" w="*"/>
                                </horizontal>
                            </linear> */}
                            <linear orientation="horizontal" w="*" h="24" marginTop="5">
                                <horizontal w="0" h="*" layout_weight="2" >
                                    <text text="是否安装：" textColor="#616161" textSize="15" w="*"/>
                                </horizontal>
                                <horizontal w="0"  h="*" layout_weight="3" >
                                    <text id="app_install" text="{{app_install}}" textColor="#616161" textSize="15" w="*"/>
                                </horizontal>
                                <horizontal w="0" layout_weight="2">
                                    <card w="*" h="24" cardCornerRadius="5dp" cardElevation="0dp" gravity="center" layout_gravity="center">
                                        <View w="*" h="*" bg="@color/colorPrimary"/>
                                        <text id="down" text="下载" color="#FFFFFF"  gravity="center" size="14" bg="?attr/selectableItemBackground" clickable="true"/>
                                    </card>
                                </horizontal>
                            </linear>
                        </linear>
                    </linear>
                    <View w="*" h="1" bg="#E0E0E0" margin="0 10 0 0"/>

                </vertical>
            </list>
            </vertical>
            <card w="60" h="60" cardCornerRadius="30dp" cardElevation="0dp" layout_gravity="bottom|center" margin="16" >
                <img id="start" w="*" h="*" />
                <img id="fab_img" w="30" h="30" layout_gravity="center" src="https://gitee.com/wupk/auto.test/raw/master/img/start.png" tint="#ffffff"/>
            </card>
        </frame>
    </vertical>
);

ui.appbar.backgroundDrawable = GradientDrawable("LEFT_RIGHT", ["#FF0081FF", "#FF1CBBB4"]);
ui.start.backgroundDrawable = GradientDrawable("LEFT_RIGHT", ["#FF0081FF", "#FF1CBBB4"]);
var storage = storages.create("video_app");

var num = 0;
let json = null;
var num_ = 1;
//是否开启滑动模式，已经开启不在开启，保证之开启一次，避免冲突
var is_start_slide = false;
//程序已经执行次数
var run_num = 1;
//单个app的开始时间和结束时间
var start_run_time;
var end_run_time;
//已经选中的app
let list = JSON.parse("[]");
//初始化配置参数
setTimeout(initConfig,500);
//获取网络数据
threads.start(getDatas);

function initConfig(){
    var runTag = "";
    random_up = storage.get("random_up", true);
    auto_up_down = storage.get("auto_up_down", true);
    if(random_up){
        runTag ="随机点赞、";
    }
    if(storage.get("auto_refresh", true)){
        runTag +="自动刷新、";
    }
    if(auto_up_down){
        runTag +="随机滑动";
    }
    ui.app_params_desc.setText(
            "单个APP启动等待时间 "+storage.get("startWaitTime", "8")+"秒，"+
            "单个APP运行时间 "+storage.get("oneAppRunTime", "30")+"分，"+
            "本次程序执行次数 "+storage.get("everydayNumber", "4")+"次。"+
            "\n已开启的任务："+ runTag);

    ui.back.on("click",function(){
        if(is_start_slide){
            confirm("当前程序正在执行是否退出?").then(value=>{
                if(value){
                    ui.finish();
                }
            });
        }else{
            ui.finish();
        }
    });
     
    ui.start.on("click", function(){
        
        if(is_start_slide){
            new com.stardust.autojs.core.ui.inflater.util.Drawables().loadInto(ui.fab_img, 
                android.net.Uri.parse("https://gitee.com/wupk/auto.test/raw/master/img/start.png"));
            is_start_slide = false;
            threads.shutDownAll();
            console.hide();
            device.cancelKeepingAwake();
        }else{
            if(json!=null && json.length>0){
                if(num==0){
                    toast("请选中要执行的App!");
                    return;
                }
                //清除已经保存运行的app
                storage.clear();
                for(var i=0;i<json.length;i++){
                    if(json[i].app_check && json[i].app_status.equals("1")){
                        storage.put(json[i].app_package,json[i].app_check);
                    }
                }
                device.keepScreenOn();
                new com.stardust.autojs.core.ui.inflater.util.Drawables().loadInto(ui.fab_img, 
                    android.net.Uri.parse("https://gitee.com/wupk/auto.test/raw/master/img/end.png"));
                threads.start(run);
            }
        }
    });
    
}

ui.app_start_setting.on("click",function(){
        let dialogView = ui.inflate(
            <vertical id="start_params">
                    <text textSize="22sp" textStyle="bold" textColor="black" text="配置启动参数" w="*" gravity="center_vertical" margin="15"/>

                    <horizontal w="*" h="1px" margin="0 0 0 5" bg='#E0E0E0'></horizontal>
                    <horizontal h="30" margin="10 0 10 0">
                        <text textSize="14sp" textColor="black" text="App启动等待时间" w="0" h="*" gravity="center_vertical" layout_weight="1"/>
                        <input id="startWaitTime" textSize="14sp" textColor="black" bg="#ffffff" inputType="number" w="90" h="40"  text="8" hint="8" />
                        <text textSize="14sp"  text="秒" textColor="black" gravity="center_vertical"  w="auto" h="*"/>
                    </horizontal>

                    <horizontal w="*" h="1px" margin="0 5 0 5" bg='#E0E0E0'></horizontal>

                    <horizontal h="30" margin="10 0 10 0">
                        <text textSize="14sp" textColor="black" text="单个App运行时间" w="auto" h="*" gravity="center_vertical" layout_weight="1"/>
                        <input id="oneAppRunTime" textSize="14sp" textColor="black" bg="#ffffff" inputType="number" w="90" h="40"  text="30" hint="30" />
                        <text textSize="14sp"  text="分" textColor="black" gravity="center_vertical" w="auto" h="*"/>
                    </horizontal>

                    <horizontal w="*" h="1px" margin="0 5 0 5" bg='#E0E0E0'></horizontal>

                    <horizontal h="30" margin="10 0 10 0">
                        <text textSize="14sp" textColor="black" text="程序每日执行次数" w="auto" h="*" gravity="center_vertical" layout_weight="1"/>
                        <input id="everydayNumber" textSize="14sp" textColor="black" bg="#ffffff" inputType="number" w="90" h="40"  text="4" hint="4"/>
                        <text textSize="14sp"  text="轮" textColor="black" gravity="center_vertical" w="auto" h="*"/>
                    </horizontal>

                    <horizontal w="*" h="1px" margin="0 5 0 5" bg='#E0E0E0'></horizontal>
                    <horizontal h="30" margin="10 0 10 0">
                        <Switch textSize="14sp" textColor="black" id="random_up"  text="视频随机点赞(10%)" checked="true" layout_weight="1" h="*"/>
                    </horizontal>
                    
                    <horizontal w="*" h="1px" margin="0 5 0 5" bg='#E0E0E0'></horizontal>
                    <horizontal h="30" margin="10 0 10 0">
                        <Switch textSize="14sp" textColor="black" id="auto_refresh"  text="随机时间重新获取视频" checked="true" layout_weight="1" h="*"/>
                    </horizontal>
                    <horizontal w="*" h="1px" margin="0 5 0 5" bg='#E0E0E0'></horizontal>

                    <horizontal h="30" margin="10 0 10 0">
                        <Switch textSize="14sp" textColor="black" id="auto_up_down"  text="自动上滑、下滑" checked="true" layout_weight="1" h="*"/>
                    </horizontal>
                    <horizontal w="*" h="1px" margin="0 5 0 5" bg='#E0E0E0'></horizontal>
                    <horizontal w="*" margin="0 15 0 20" gravity="center">
                        <button id="btn_confirm" text="确定" h="45" w="200sp" textColor="#FFFFFF" gravity="center" textSize="15sp" bg="#FF1CBBB4" />
                    </horizontal>
                </vertical>, null, false);
        dialogView.startWaitTime.setText(storage.get("startWaitTime", "8"));
        dialogView.oneAppRunTime.setText(storage.get("oneAppRunTime", "30"));
        dialogView.everydayNumber.setText(storage.get("everydayNumber","4"));
        dialogView.random_up.checked = storage.get("random_up", true);
        dialogView.auto_refresh.checked = storage.get("auto_refresh", true);
        dialogView.auto_up_down.checked = storage.get("auto_up_down", true);

        dialogView.btn_confirm.on("click",function(){
            storage.put("startWaitTime", dialogView.startWaitTime.getText().toString());
            storage.put("oneAppRunTime", dialogView.oneAppRunTime.getText().toString());
            storage.put("everydayNumber", dialogView.everydayNumber.getText().toString());

            storage.put("random_up", dialogView.random_up.isChecked());
            storage.put("auto_refresh", dialogView.auto_refresh.isChecked());
            storage.put("auto_up_down", dialogView.auto_up_down.isChecked());
            random_up = dialogView.random_up.isChecked();
            auto_up_down = dialogView.auto_up_down.isChecked();
            var runTag = "";
            if(dialogView.random_up.isChecked()){
                runTag ="随机点赞、";
            }
            if(dialogView.auto_refresh.isChecked()){
                runTag +="自动刷新、";
            }
            if(auto_up_down){
                runTag +="随机滑动";
            }
            ui.app_params_desc.setText(
                    "单个APP启动等待时间 "+dialogView.startWaitTime.getText().toString()+"秒，"+
                    "单个APP运行时间 "+dialogView.oneAppRunTime.getText().toString()+"分，"+
                    "本次程序执行次数 "+dialogView.everydayNumber.getText().toString()+"次。"+
                    "\n已开启的任务："+ runTag);
            alertDialog.dismiss();
        });
        alertDialog = dialogs.build({
            customView: dialogView,
            wrapInScrollView: false,
            autoDismiss: true,
            cancelable: true,
        }).show();
});

/**
 * 开始运行程序
 */
function run(){
    // var Url = "https://gitee.com/wupk/auto.test/raw/master/test/video/video_run.js";
    // var res_script = http.get(Url, {
    //     headers: {
    //         'Accept-Language': 'en-us,en;q=0.5',
    //         'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
    //     }
    // });
    // var video = res_script.body.string();
    // engines.execScript("test", video);
    
    var t = 0;
    for(var i=0;i<json.length;i++){
        if(json[i].app_check){
            list[t] = json[i];
            t++;
        }
    }
    device.keepScreenOn();
    threads.start(main);
}

/**
 * 转换成系统支持的颜色
 * @param {颜色} color 
 */
function Color(color) {
    return android.graphics.Color.parseColor(color);
}

/**
 * 配置渐变色
 * @param {方向} orientation 
 * @param {颜色数组} color 
 */
function GradientDrawable(orientation, color) {
    var colors = [];
    color.forEach(color => colors.push(Color(color)));
    return new android.graphics.drawable.GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation[orientation], colors);
}

function getDatas(){
    
    var Url = "https://gitee.com/wupk/auto.test/raw/master/test/dats.json";
    var res_script = http.get(Url, {
        headers: {
            'Accept-Language': 'en-us,en;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
        }
    });
    var temp = res_script.body.string();
    if (res_script.statusCode == 200){
        json = JSON.parse(temp);
        for(var i=0;i<json.length;i++){
            json[i].app_number = i+1;
            var appName = app.getAppName(json[i].app_package);
            if(appName==null){
                json[i].app_install = "未安装";
                json[i].app_status = "0";
            }else{
                json[i].app_install = "已安装";
                json[i].app_status = "1";
            }
            var app_checked = storage.get(json[i].app_package,false);
            json[i].app_check = app_checked;
            if(app_checked){
                num++;
            }
        }
        //获取到数据以后重新计算一下app是否安装，和已经缓存的数据，缓存的数据放到最上方
        ui.post(function(action, delay){
            setDatas(json);
        });
    }
}

function setDatas(json){
    ui.video_list.setDataSource(json);
    toast("已经选中 "+num+" 个App");
    ui.video_list.on("item_click",function(item,i,itemView,listView){
        //判断是否选中，已经选中的进行反选
        var check = !itemView.app_check.isChecked();
        if(item.app_status.equals("1")){
            itemView.app_check.checked = check;
            item.app_check = check;
            if(check){
                num++;
            }else{
                num--;
            }
            ui.post(function(action, delay){
                toast("已经选中 "+num+" 个App");
            });
        }else{
            ui.post(function(action, delay){
                toast(item.app_name +"：未安装支持的APP");
            });
        }
    });
    ui.video_list.on("item_bind",function(itemView,itemHolder){
        itemView.copy.on("click", function(){
            let item = itemHolder.item;
            setClip(item.app_yqm);
            toast("复制成功！");
        });
        itemView.down.on("click", function(){
            let item = itemHolder.item;
            app.openUrl(item.app_down);
        });
        itemView.app_check.on("check" ,function(isChecked,view){
            let item = itemHolder.item;
            item.app_check = isChecked;
        });
    });
}

/**
 * 主函数
 */
function main(){
    //显示控制台
    var middle = device.width / 2 - 400;
    console.setSize(800, 800);
    console.setPosition(middle, 100);
    console.setTitle("阅读助手");
    console.show();

    var everyday_num = parseInt(storage.get("everydayNumber","4"));
    var oneAppRunTime = parseInt(storage.get("oneAppRunTime", "30"));
    var app_name = "";
    for(var i=0;i<list.length;i++){
        app_name+=list[i].app_name+"、";
        list[i].run_tag = true;
    }
    logError("本次执行的APP："+app_name);

    //程序启动时间,不可修改
    var startTime = new Date().getTime();
    //计算程序结束时间，到达结束时间后重新初始化参数
    var end_time  = new Date( startTime + oneAppRunTime * list.length * 60 * 1000).getTime();
    
    setInterval(function(){
        for (var i = 0; i < list.length; i++) {

            var nowTime = new Date().getTime();
            var endTime = new Date(startTime.valueOf() + oneAppRunTime * i * 60 *  1000).getTime();
            var nextTime = new Date(startTime.valueOf() + oneAppRunTime * (i+1) * 60  * 1000).getTime();

            if(nowTime>=endTime && nowTime<= nextTime){
                if(list[i].run_tag){
                    list[i].run_tag = false;
                    logInfo("启动："+list[i].app_name);

                    start_run_time = list[i].app_start_time;
                    end_run_time = list[i].app_end_time;
                    
                    app.launchPackage(list[i].app_package);
                    threads.start(stratRun);
                }
            }

            if(nowTime>=end_time){
                startTime = nowTime;
                run_num++;
                end_time = new Date( nowTime.valueOf() + oneAppRunTime * list.length * 60 * 1000).getTime();
                for(var i=0;i<list.length;i++){
                    list[i].run_tag = true;
                }
            }

            if(run_num > everyday_num){
                logInfo("已经到达执行次数，停止运行...");
                threads.shutDownAll();
                console.hide();
                device.cancelKeepingAwake();
            }
        }
    },1000);
}

/**
 * 开启滑动模式
 * 单独线程
 */
function stratRun(){

    if(!is_start_slide){
        is_start_slide = true;

        setInterval(function(){
            huadong();
        },1000);
        
        //单独开启线程用于判断当前app,和校验规则，不和主线程发生冲突
        setInterval(function(){
            autopage();
            
        },1000);
    }
}

/**
 * 校验当前打开的app是否是滑动的app
 * 
 */
function val(package){
    
}


/**
 * 滑动模式
 */
function huadong(){
    //随机等待时间random（最小值，最大值）根据需要更改数值（单位秒）
    var time_random=random(parseInt(start_run_time)*1000,parseInt(end_run_time)*1000);
    //version 1.0
    // swipe(device.width/2+200,device.height-200 ,device.width/2,height_2,duration);
    var height = parseInt(device.height);
    var width = parseInt(device.width);
    //version 1.1

    var x1 = width/2+random(100,200);
    var y1 = height-random(50,300);
    var y2 = random(100,150);
    
    if(auto_up_down && num_>10){
        var sjs = random(1,100);
        if(sjs>30){//随机上滑
            var x2 = width/2 + random(50,120);
            var y2 = random(80,180);
            randomSwipe(x2,height-200 ,x2,y2);
        }else{//随机下滑
            var x2 = random(50,120);
            var d = random(200, 320)
            swipe(x2,150, x2,height-200 ,d);
        }
    }else{
        randomSwipe(x1,y1 , x1,y2);
    }

    logInfo("总浏览视频: "+num_+"次 ~ "+time_random);
    num_++;
                                                      
    if(random_up && num_>10){
        var r = random(4000,8000);
        //400/4000  1/10
        if(r<4400){
            logInfo("执行 【随机点赞】 事件...");
            //经软件判断在屏幕左下2/3处执行双击点赞事件最合理，不会有覆盖
            click(100 + random(80,120) , height/2 + random(80,120));
            sleep(100);
            click(100 + random(80,120) , height/2 + random(80,120));
        }
    }

    sleep(time_random);
}

/**
 * 自动检测页面内容
 */
function autopage(){
    if(className("android.widget.Button").text("继续看视频").exists()){
        className("android.widget.Button").text("继续看视频").findOnce().click();
        logInfo("执行 【继续看视频】 事件...");
    }
    if(className("android.widget.TextView").text("点击进入直播间").exists()){
        logInfo("当前视频是直播，直接跳过...");
        swipe(random(80,180),device.height-200 ,random(80,180),150,200);
    }
    if(className("android.widget.TextView").text("点击打开图集").exists()){
        logInfo("当前视频是图片，直接跳过...");
        swipe(random(80,180),device.height-200 ,random(80,180),150,200);
    }
    if(className("android.widget.TextView").text("点击打开长图").exists()){
        logInfo("当前视频是图片，直接跳过...");
        swipe(random(80,180),device.height-200 ,random(80,180),150,200);
    }

    if(className("android.view.View").text("立即签到").exists()){
        className("android.view.View").text("立即签到").findOnce().click();
        logInfo("执行 【立即签到】 事件...");
    }

    if(id("btn_confirm").exists()){
        //刷宝短视频，直播任务
        var dz_x1 = 100 + random(80,180);
        var dz_y1 = device.height*2/3 + random(80,180);
        click(dz_x1,dz_y1);
    }

    if(id("btn_close").exists()){
        id("btn_close").click();
    }

    if(id("iv_close").exists()){
        id("iv_close").click();
    }
    
}

/**
 * 真人模拟滑动函数
 *
 * 传入值：起点终点坐标
 * 效果：模拟真人滑动
 */
function randomSwipe(sx, sy, ex, ey) {
    //设置控制点极限距离
    var leaveHeightLength = 300

    //根据偏差距离，应用不同的随机方式
    var my = (sy + ey) / 2
    var y2 = my + random(0, leaveHeightLength)
    var y3 = my - random(0, leaveHeightLength)

    var lx = (sx - ex) / 3
    if (lx < 0) { lx = -lx }
    var x2 = sx + lx / 2 + random(0, lx)
    var x3 = sx + lx + lx / 2 + random(0, lx)

    //获取运行轨迹，及参数
    var time = [0, random(200, 450)]
    var track = bezierCreate(sx, sy, x2, y2, x3, y3, ex, ey)
    gestures(time.concat(track))
}

/**
 * 获取滑动坐标组
 * @param {*} x1
 * @param {*} y1
 * @param {*} x2
 * @param {*} y2
 * @param {*} x3
 * @param {*} y3
 * @param {*} x4
 * @param {*} y4
 */
function bezierCreate(x1, y1, x2, y2, x3, y3, x4, y4) {
    //构建参数
    var h = 100;
    var cp = [{ x: x1, y: y1 + h }, { x: x2, y: y2 + h }, { x: x3, y: y3 + h }, { x: x4, y: y4 + h }];
    var numberOfPoints = 100;
    var curve = [];
    var dt = 1.0 / (numberOfPoints - 1);

    //计算轨迹
    for (var i = 0; i < numberOfPoints; i++) {
        var ax, bx, cx;
        var ay, by, cy;
        var tSquared, tCubed;
        var result_x, result_y;

        cx = 3.0 * (cp[1].x - cp[0].x);
        bx = 3.0 * (cp[2].x - cp[1].x) - cx;
        ax = cp[3].x - cp[0].x - cx - bx;
        cy = 3.0 * (cp[1].y - cp[0].y);
        by = 3.0 * (cp[2].y - cp[1].y) - cy;
        ay = cp[3].y - cp[0].y - cy - by;

        var t = dt * i
        tSquared = t * t;
        tCubed = tSquared * t;
        result_x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
        result_y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
        curve[i] = {
            x: result_x,
            y: result_y
        };
    }

    //轨迹转路数组
    var array = [];
    for (var i = 0; i < curve.length; i++) {
        try {
            var j = (i < 100) ? i : (199 - i);
            xx = parseInt(curve[j].x)
            yy = parseInt(Math.abs(100 - curve[j].y))
        } catch (e) {
            break
        }
        array.push([xx, yy])
    }

    return array
}


/**
 * 格式化时间
 */
function getTime() {
    var fmt = "YYYY-MM-dd hh:mm:ss";
    var d = new Date();
    var hh = d.getHours();
    var mm = d.getMinutes();
    if (mm < 30) {
        mm = 30
    } else {
        hh += 1;
        mm = 0
    }
    var o = {
        "Y+": d.getYear() + 1900,
        "M+": d.getMonth() + 1,
        "d+": d.getDate(),
        "h+": hh,
        "m+": mm,
        "s+": 0
    };
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 4) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    fmt = fmt.replace(/-/g, '/');
    return fmt;
}

// 获取时分秒用于记录日志
function logCommon(msg) {
    console.log(formatDate(getNow()) + " " + msg);
}
function logInfo(msg) {
    console.info(formatDate(getNow()) + " " + msg);
}
function logWarn(msg) {
    console.warn(formatDate(getNow()) + " " + msg);
}
function logError(msg) {
    console.error(formatDate(getNow()) + " " + msg);
}

// 时间戳转时间字符串
function add0(m) {
    return m < 10 ? '0' + m : m
}
// 根据时间偏移值计算真实时间
function getNow() {
    var now = new Date().getTime();
    return now;
}
function add00(m) {
    if (m < 10) {
        return '00' + m;
    } else if (m < 100) {
        return '0' + m;
    } else {
        return m;
    }
}

function formatDate(needTime) {
    //needTime是整数，否则要parseInt转换
    var time = new Date(parseInt(needTime));
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return add0(h) + ':' + add0(mm) + ':' + add0(s);
}